# To change this template, choose Tools | Templates
# and open the template in the editor.

require 'matrix'
require 'utility/vec_utils'

class QuadraticRegression

  attr_accessor :vector

  def initialize mx,y,degree=2
    x= VecUtils.matrix_av_vector(mx)
    @vector= self.train(x,y,degree)
  end
  # Update delle variabili
  def update(mx,y,degree=2)
     x= VecUtils.matrix_av_vector(mx)
     uvector= self.train(x,y,degree)
     
    v=[]

    (0..uvector.size-1).each{|i|
      v.push((uvector[i]+self.vector[i])/2)
    }

    self.vector= v

  end
def train x, y, degree
  x_data = x.map { |xi| (0..degree).map { |pow| (xi**pow).to_f } }

  mx = Matrix[*x_data]
  my = Matrix.column_vector(y)

  return ((mx.t * mx).inv * mx.t * my).transpose.to_a[0]
end
def regressione mx
  x= VecUtils.matrix_av_vector(mx)
  y= []
  x.each{|e|
    value=0
    self.vector.inject(0) { |i,v|
    
    value= value+v*(e**i)
    
    i= i+1 }
  y.push(value.round)

  }

  return y
end
def vector
  @vector
end
def QuadraticRegression.test()
    x = [[71,73,64,65,61,70,65,72,63,67,64]]
    y = [160,183,154, 168, 159, 180, 145, 210, 132, 168, 141]

    r= QuadraticRegression.new(x,y)

    p '<---------------------------->'
    p 'Test regressione polinomiale'
    p '<--------->'
    p 'Dati'
    p 'intercetta'
    p r.vector
    p 'fine dati'
    p '<--------->'
    p 'test con valore 70'
    p 'valore atteso: [176.51,185]'
    p r.regressione([[70,72]])
    p '<---------------------------->'
end
end
